﻿using System;
using System.IO;
using ParkService.Core;
using Serilog;
using Serilog.Formatting;
using Topshelf;
using Topshelf.Logging;

namespace ParkService
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        static void Main()
        {
            try
            {
                var rc = (int)HostFactory.Run(x =>
                {
                    Log.Logger = new LoggerConfiguration()
                        .MinimumLevel.Debug()
                        .WriteTo.ColoredConsole()
                        .WriteTo.RollingFile("logs/{Date}.txt")
                        .CreateLogger();
                    x.UseSerilog();

                    Log.Logger.Information("安装成系统服务请查看 http://docs.topshelf-project.com/en/latest/overview/commandline.html");
                    Log.Logger.Information($"或者运行 {Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)} help");

                    // 基本的配置
                    x.RunAsLocalSystem();
                    x.SetServiceName("ParkService");
                    x.SetDisplayName("ParkService");
                    x.SetDescription("停车服务");
                    x.StartAutomatically();
                    x.EnableShutdown();

                    string _serverWsUrl = Properties.Settings.Default.ServerWsUrl;
                    int _port = Properties.Settings.Default.Port;
                    int _hubId = Properties.Settings.Default.HubId;

                    x.Service(settings => new WindowService(_serverWsUrl, _port, _hubId), s =>
                    {
                        s.BeforeStartingService(_ => Console.WriteLine("BeforeStart"));
                        s.BeforeStoppingService(_ => Console.WriteLine("BeforeStop"));
                    });

                    x.SetStartTimeout(TimeSpan.FromSeconds(10));
                    x.SetStopTimeout(TimeSpan.FromSeconds(10));

                    x.EnableServiceRecovery(r =>
                    {
                        r.RestartService(3);
                        //r.RunProgram(7, "ping google.com");
                        //r.RestartComputer(5, "message");

                        r.OnCrashOnly();
                        r.SetResetPeriod(2);
                    });

                    x.AddCommandLineDefinition("serverWsUrl", v => _serverWsUrl = v);
                    x.AddCommandLineDefinition("port", v => int.TryParse(v, out _port));
                    x.AddCommandLineDefinition("hubId", v => int.TryParse(v, out _hubId));

                    x.OnException((exception) =>
                    {
                        Console.WriteLine("Exception thrown - " + exception.Message);
                    });
                });
                Environment.ExitCode = rc;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


        }
    }
}
